<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CTYun Docker Registry UI</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .container { max-width: 1200px; }
        .form-container { margin-top: 2rem; }
        .copy-btn {
            cursor: pointer;
            padding: 4px 8px;
            background: #f8f9fa;
            border: none;
            border-radius: 4px;
        }
        .copy-btn:hover {
            background: #e9ecef;
        }
        .command-block {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 4px;
            margin: 0.5rem 0;
        }
        .command-line {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 0.5rem 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="mt-5">CTYun Docker Registry UI</h1>

        <!-- 操作步骤 -->
        <div class="card mb-4 mt-4">
            <div class="card-header">
                <h4>操作步骤</h4>
            </div>
            <div class="card-body">
                <ol class="list-group list-group-numbered">
                    <li class="list-group-item">
                        <div>配置 docker 用户组（仅首次需要）：</div>
                        <div class="command-block">
                            <div class="command-line">
                                <code>sudo usermod -aG docker $USER</code>
                                <button class="copy-btn" onclick="copyText('sudo usermod -aG docker $USER')">
                                    <i class="bi bi-clipboard"></i> 复制命令
                                </button>
                            </div>
                            <div class="alert alert-info mt-2 mb-0">
                                <i class="bi bi-info-circle"></i> 执行后需要重新登录系统生效
                            </div>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div>执行以下登录指令：</div>
                        <div class="command-block">
                            {% for line in login_info %}
                                {% if '登录指令:' in line %}
                                <div class="command-line">
                                    <code>{{ line.replace('登录指令:', '').strip() }}</code>
                                    <button class="copy-btn" onclick="copyLoginCommand('{{ line.replace('登录指令:', '').strip() }}')">
                                        <i class="bi bi-clipboard"></i> 复制登录命令
                                    </button>
                                </div>
                                {% elif '过期时间:' in line %}
                                <div class="alert alert-warning mt-2 mb-0">
                                    <i class="bi bi-clock"></i> {{ line }}
                                </div>
                                {% endif %}
                            {% endfor %}
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div>拉取镜像示例：</div>
                        <div class="command-block">
                            <div class="command-line">
                                <code>docker pull registry.cn-hncs1.ctyun.cn/robert/{镜像名称}:{版本名称}</code>
                                <button class="copy-btn" onclick="copyText('docker pull registry.cn-hncs1.ctyun.cn/robert/')">
                                    <i class="bi bi-clipboard"></i>
                                </button>
                            </div>
                            <div class="alert alert-info mt-2">
                                <i class="bi bi-info-circle"></i> 注意：不要使用 sudo 执行 docker 命令，否则可能导致认证失败
                            </div>
                        </div>
                    </li>
                </ol>
            </div>
        </div>

        <!-- 推送镜像表单 -->
        <div class="card mb-4">
            <div class="card-header">
                <h4>推送镜像</h4>
            </div>
            <div class="card-body">
                <form id="pushForm" class="needs-validation" novalidate>
                    <div class="row">
                        <div class="col-md-5">
                            <div class="mb-3">
                                <label for="imageName" class="form-label">镜像名称</label>
                                <input type="text" class="form-control" id="imageName" name="image_name" required
                                       placeholder="例如: nginx">
                                <div class="form-text">本地镜像名称</div>
                            </div>
                        </div>
                        <div class="col-md-5">
                            <div class="mb-3">
                                <label for="imageTag" class="form-label">标签</label>
                                <input type="text" class="form-control" id="imageTag" name="tag" required
                                       placeholder="例如: latest">
                                <div class="form-text">镜像版本标签</div>
                            </div>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary mb-3 w-100">推送镜像</button>
                        </div>
                    </div>
                </form>
                <div id="result"></div>
                <div id="commandPreview" class="d-none">
                    <h5 class="mt-3">执行以下命令：</h5>
                    <div class="command-block">
                        <div class="command-line">
                            <code id="tagCommand"></code>
                            <button class="copy-btn" onclick="copyCommand('tagCommand')">
                                <i class="bi bi-clipboard"></i>
                            </button>
                        </div>
                        <div class="command-line">
                            <code id="pushCommand"></code>
                            <button class="copy-btn" onclick="copyCommand('pushCommand')">
                                <i class="bi bi-clipboard"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 镜像列表 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="mb-0">镜像列表</h4>
                <div>
                    <button class="btn btn-outline-secondary me-2" onclick="triggerUpdate()">
                        <i class="bi bi-arrow-repeat"></i> 更新登录信息
                    </button>
                    <button class="btn btn-outline-primary" onclick="location.reload()">
                        <i class="bi bi-arrow-clockwise"></i> 刷新页面
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>镜像名称</th>
                                <th>所属组织</th>
                                <th>类型</th>
                                <th>版本数</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for image in image_list %}
                            <tr>
                                <td>{{ image.name }}</td>
                                <td>{{ image.namespace }}</td>
                                <td>
                                    <span class="badge {% if image.is_public == '私有' %}bg-primary{% else %}bg-success{% endif %}">
                                        {{ image.is_public }}
                                    </span>
                                </td>
                                <td>{{ image.tag_count }}</td>
                                <td>{{ image.updated_time }}</td>
                                <td>
                                    <button class="btn btn-sm btn-outline-secondary" 
                                            onclick="copyPullCommand('{{ image.name }}')">
                                        复制拉取命令
                                    </button>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 复制文本功能
        async function copyText(text) {
            try {
                // 首先尝试使用 Clipboard API
                if (navigator.clipboard && window.isSecureContext) {
                    await navigator.clipboard.writeText(text);
                    showToast('复制成功！');
                    return;
                }
                
                // 后备方案：创建临时文本区域
                const textArea = document.createElement('textarea');
                textArea.value = text;
                
                // 将文本区域移出可视区域
                textArea.style.position = 'fixed';
                textArea.style.left = '-999999px';
                textArea.style.top = '-999999px';
                document.body.appendChild(textArea);
                
                // 选择并复制文本
                textArea.focus();
                textArea.select();
                
                try {
                    document.execCommand('copy');
                    textArea.remove();
                    showToast('复制成功！');
                } catch (err) {
                    console.error('复制失败:', err);
                    showToast('复制失败，请手动复制');
                }
            } catch (err) {
                console.error('复制失败:', err);
                showToast('复制失败，请手动复制');
            }
        }

        // 复制拉取命令
        function copyPullCommand(imageName) {
            const command = `sudo docker pull registry.cn-hncs1.ctyun.cn/robert/${imageName}:latest`;
            copyText(command);
        }

        // 复制命令预览中的命令
        function copyCommand(elementId) {
            const command = document.getElementById(elementId).textContent;
            copyText(command);
        }

        // 表单处理
        document.getElementById('pushForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const form = e.target;
            const resultDiv = document.getElementById('result');
            const submitButton = form.querySelector('button[type="submit"]');
            const commandPreview = document.getElementById('commandPreview');
            
            // 更新命令预览
            const imageName = form.image_name.value;
            const tag = form.tag.value;
            const tagCommand = document.getElementById('tagCommand');
            const pushCommand = document.getElementById('pushCommand');
            
            tagCommand.textContent = `sudo docker tag ${imageName}:${tag} registry.cn-hncs1.ctyun.cn/robert/${imageName}:${tag}`;
            pushCommand.textContent = `sudo docker push registry.cn-hncs1.ctyun.cn/robert/${imageName}:${tag}`;
            commandPreview.classList.remove('d-none');
            
            // 禁用提交按钮
            submitButton.disabled = true;
            submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 推送中...';
            
            try {
                const formData = new FormData(form);
                const response = await fetch('/push-image', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success">
                            ${data.message}
                        </div>
                    `;
                    // 成功后刷新页面
                    setTimeout(() => location.reload(), 2000);
                } else {
                    resultDiv.innerHTML = `
                        <div class="alert alert-danger">
                            ${data.message}
                        </div>
                    `;
                }
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        发生错误: ${error.message}
                    </div>
                `;
            } finally {
                // 恢复提交按钮
                submitButton.disabled = false;
                submitButton.innerHTML = '推送镜像';
            }
        });

        // 简单的提示框
        function showToast(message) {
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 10px 20px;
                background: rgba(0,0,0,0.8);
                color: white;
                border-radius: 4px;
                z-index: 1000;
            `;
            toast.textContent = message;
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 2000);
        }

        // 复制登录命令
        function copyLoginCommand(command) {
            // 移除可能的多余空格和"登录指令:"前缀
            const cleanCommand = command.replace(/^登录指令:\s*/, '').trim();
            copyText(cleanCommand);
        }

        // 更新样式
        document.head.insertAdjacentHTML('beforeend', `
            <style>
                .command-line {
                    background: #f8f9fa;
                    padding: 0.75rem;
                    border-radius: 4px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    gap: 1rem;
                }
                .command-line code {
                    flex: 1;
                    word-break: break-all;
                    white-space: pre-wrap;
                }
                .copy-btn {
                    white-space: nowrap;
                    display: inline-flex;
                    align-items: center;
                    gap: 0.5rem;
                    padding: 0.375rem 0.75rem;
                    background: #e9ecef;
                    border: 1px solid #dee2e6;
                    border-radius: 4px;
                    cursor: pointer;
                    transition: all 0.2s;
                }
                .copy-btn:hover {
                    background: #dee2e6;
                }
                .alert-warning {
                    font-size: 0.9rem;
                }
            </style>
        `);

        // 触发更新函数
        async function triggerUpdate() {
            const button = event.target.closest('button');
            const originalText = button.innerHTML;
            
            try {
                // 更新按钮状态
                button.disabled = true;
                button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 更新中...';
                
                // 发送更新请求
                const response = await fetch('/trigger-update', {
                    method: 'POST'
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    showToast('更新任务已触发，请稍后刷新页面');
                    // 3秒后自动刷新页面
                    setTimeout(() => location.reload(), 3000);
                } else {
                    showToast('更新失败: ' + data.message);
                }
            } catch (error) {
                showToast('更新失败: ' + error.message);
            } finally {
                // 恢复按钮状态
                button.disabled = false;
                button.innerHTML = originalText;
            }
        }
    </script>
</body>
</html> 